package com.talos.ums.service.role;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.role.vo.UmsRolePageReqVO;
import com.talos.ums.controller.admin.role.vo.UmsRoleSaveReqVO;
import com.talos.ums.dal.dataobject.role.UmsRoleDO;
import com.talos.ums.dal.mysql.role.UmsRoleMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 角色表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsRoleServiceImpl implements UmsRoleService {

    @Resource
    private UmsRoleMapper roleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createRole(UmsRoleSaveReqVO createReqVO) {
        // 插入
        UmsRoleDO role = BeanUtils.toBean(createReqVO, UmsRoleDO.class);
        roleMapper.insert(role);
        // 返回
        return role.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(UmsRoleSaveReqVO updateReqVO) {
        // 校验存在
        validateRoleExists(updateReqVO.getId());
        // 更新
        UmsRoleDO updateObj = BeanUtils.toBean(updateReqVO, UmsRoleDO.class);
        roleMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Long id) {
        // 校验存在
        validateRoleExists(id);
        // 删除
        roleMapper.deleteById(id);
    }

    private void validateRoleExists(Long id) {
        if (roleMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsRoleDO getRole(Long id) {
        return roleMapper.selectById(id);
    }

    @Override
    public PageResult<UmsRoleDO> getRolePage(UmsRolePageReqVO pageReqVO) {
        return roleMapper.selectPage(pageReqVO);
    }

}
